<template>
  <ElDrawer v-model="opened" :title="formType" size="50%" destroy-on-close>
    <div v-if="isAdd">
      <el-table v-loading="loading" highlight-current-row :data="formDataArray" :border="true">
        <el-table-column label="物种分类" align="center" :show-overflow-tooltip="true" min-width="180">
          <template #default="scope">
            <el-tree-select
              v-model="scope.row.wzType"
              placeholder="请选择"
              :data="selectData"
              filterable
              check-strictly
              :disabled="isView"
              :render-after-expand="false"
              @change="tableTreeSelectChange(scope.$index, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="物种" align="center" :show-overflow-tooltip="true" min-width="180">
          <template #default="scope">
            <el-select filterable v-model="scope.row.businessId" :clearable="true" :fit-input-width="true">
              <el-option v-for="item in scope.row.wzSelectData" :key="item.id" :label="item.chName" :value="item.id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="文件名" align="center" prop="fileName" :show-overflow-tooltip="true" />
        <el-table-column label="文件大小" align="center" :show-overflow-tooltip="true" width="150">
          <template #default="scope">{{ convertBytes(scope.row.fileSize) }}</template>
        </el-table-column>
        <el-table-column label="文件类型" align="center" prop="fileSuffix" :show-overflow-tooltip="true" width="100" />
        <el-table-column fixed="right" label="操作" align="center" width="80">
          <template #default="scope">
            <el-button type="primary" link size="small" :icon="Delete" @click.stop="deleteFileList(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="isEdit">
      <ElFormItem label="物种" :label-width="100">
        <el-tree-select
          v-model="editWzId"
          placeholder="请选择"
          :data="selectData"
          filterable
          check-strictly
          :disabled="isView"
          :render-after-expand="false"
          @change="treeSelectChange" />
      </ElFormItem>
      <ElFormItem label="物种" :label-width="100">
        <el-select filterable v-model="editBusinessId" :clearable="true" :fit-input-width="true">
          <el-option v-for="item in wzSelectOption" :key="item.id" :label="item.chName" :value="item.id" />
        </el-select>
      </ElFormItem>
    </div>
    <div v-if="isView">
      <div v-if="form.type === 'IMAGE'"><el-image :src="form.fileUrl" /></div>
      <div v-if="form.type === 'VIDEO'">
        <video ref="videoPlayer" controls :src="form.fileUrl" style="height: 500px; width: 100%"></video>
      </div>
    </div>
    <template #footer>
      <div style="display: none">
        <el-upload
          ref="uploadRef"
          v-model:file-list="fileList"
          action="#"
          list-type="picture-card"
          :multiple="true"
          :limit="limit"
          :http-request="handleHttpUpload"
          :before-upload="beforeUpload"
          :on-exceed="handleExceed"
          :on-success="uploadSuccess"
          :accept="'.mp4,image/jpeg'"
          :show-file-list="false">
          <ElButton ref="uploadBtnRef" type="primary">新增</ElButton>
        </el-upload>
      </div>
      <ElButton type="primary" @click="onChooseFile" v-if="isAdd">新增</ElButton>
      <ElButton type="success" @click="onSaveClicked" v-if="!isView">保存</ElButton>
      <ElButton @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Delete } from '@element-plus/icons-vue'
import { FormType } from '@/enums'
import type { UploadProps, UploadFile, UploadUserFile, UploadRequestOptions, UploadInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { uploadImg } from '@/api/modules/upload'
import { convertBytes } from '@api/tby/common/common'
import { EducationView, saveEducationView, getEducationViewDetail, updateEducationView } from '@api/tby/education/educationView'
import { optionsSpeciesCategory } from '@api/tby/common/speciesCategory'
import { AnimalPlant } from '@api/tby/summarize/animalPlant/interface'
import { listAnimalPlant, getAnimalPlantDetail } from '@api/tby/summarize/animalPlant'

const videoPlayer = ref(null)
const uploadRef = ref<UploadInstance>()
const uploadBtnRef = ref()
const fileList = ref<UploadUserFile[]>([])
const opened = ref(false)
const loading = ref(true)
const formType = ref<FormType>()
const limit = ref(10)
const fileIndex = ref(1)
const formDataArray = ref<EducationView.WzForm[]>([])
const selectData = ref<OptionType[]>([])
const wzSelectOption = ref<AnimalPlant.Record[]>([])

const editWzId = ref<number | undefined>()
// 修改时使用，要修改的业务id
const editBusinessId = ref<number | undefined>()
// 要修改的ids
const ids = ref('')
const form = ref<Partial<EducationView.WzForm>>({})

onMounted(async () => {
  console.log('进来了')
})

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

// 是否为修改
const isEdit = computed(() => {
  return formType.value === FormType.EDIT
})

const openBatch = async (paramIds: string) => {
  editBusinessId.value = undefined
  formType.value = FormType.EDIT
  await loadSpeciesCategory()
  await loadAnimalPlant()
  ids.value = paramIds
  opened.value = true
}

const loadAnimalPlant = async (typeLevel?: number) => {
  let query: AnimalPlant.Query = { current: 0, size: 10000 }
  if (typeLevel) {
    query.typeLevel = typeLevel
  }
  let response = await listAnimalPlant(query)
  console.log(response)
  wzSelectOption.value = response.data
}

const treeSelectChange = async (value?: number) => {
  editBusinessId.value = undefined
  await loadAnimalPlant(value)
}

const tableTreeSelectChange = async (index: number, data: EducationView.WzForm) => {
  let query: AnimalPlant.Query = { current: 0, size: 10000 }
  if (data.wzType) {
    query.typeLevel = data.wzType
  }
  let response = await listAnimalPlant(query)
  data.wzSelectData = response.data
}

const loadSpeciesCategory = async () => {
  selectData.value = []
  optionsSpeciesCategory().then(({ data }) => {
    selectData.value = data
  })
}

const open = async (type: FormType, id?: number) => {
  formDataArray.value = []
  fileList.value = []
  fileIndex.value = 1
  await loadSpeciesCategory()
  formType.value = type
  opened.value = true
  if (isAdd.value) {
    loading.value = false
    return
  } else if (isEdit.value) {
    if (!id) {
      ElMessage({
        message: `请选择要修改的数据`,
        type: 'error'
      })
      return
    }
    ids.value = id + ''
    try {
      const { data } = await getEducationViewDetail(id!)
      // 获取物种分类的id
      let response = await getAnimalPlantDetail(data.businessId)
      editWzId.value = response.data.typeLevel
      await loadAnimalPlant(editWzId.value)
      loading.value = false
      editBusinessId.value = data.businessId
    } finally {
      loading.value = false
    }
  } else if (isView.value) {
    try {
      const { data } = await getEducationViewDetail(id!)
      loading.value = false
      form.value = data
      if (videoPlayer.value) {
        videoPlayer.value.play()
      }
    } finally {
      loading.value = false
    }
  }
  loading.value = false
  console.log(id, isView)
}

function close() {
  loading.value = true
  opened.value = false
  formDataArray.value = []
  fileList.value = []
  fileIndex.value = 1
}

const onChooseFile = () => {
  uploadBtnRef.value.$el.click()
}

const onSaveClicked = () => {
  if (isAdd.value === true) {
    if (formDataArray.value.length === 0) {
      ElMessageBox.alert(`请选择物种`, '错误描述', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return
    }
    for (let i = 0; i < formDataArray.value.length; i++) {
      console.log(formDataArray.value[i].businessId)
      if (formDataArray.value[i].businessId === undefined || formDataArray.value[i].businessId === 0) {
        ElMessageBox.alert(`第${i + 1}条，请选择物种`, '错误描述', {
          confirmButtonText: '我已知晓',
          type: 'error'
        })
        return
      }
    }
    let formData: EducationView.Form[] = []
    formDataArray.value.forEach(element => {
      formData.push({
        id: element.id,
        category: element.category,
        type: element.type,
        businessId: element.businessId,
        fileUrl: element.fileUrl,
        fileSize: element.fileSize,
        fileName: element.fileName,
        fileSuffix: element.fileSuffix
      })
    })
    saveEducationView(JSON.stringify(formData)).then(() => {
      sendSuccess()
      close()
    })
  } else if (isEdit.value === true) {
    if (!editBusinessId.value) {
      ElMessageBox.alert(`请选择物种`, '错误描述', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return
    }
    updateEducationView(ids.value, editBusinessId.value).then(() => {
      sendSuccess()
      close()
    })
  }
}

const onCancelClicked = () => {
  sendSuccess()
  close()
}

/**
 * @description 图片上传
 * @param options upload 所有配置项
 * */
const handleHttpUpload = async (options: UploadRequestOptions) => {
  let formData = new FormData()
  formData.append('file', options.file)
  try {
    const { data } = await uploadImg(formData)
    options.onSuccess(data)
  } catch (error) {
    options.onError(error as any)
  }
}

/**
 * @description 文件上传之前判断
 * @param rawFile 选择的文件
 * */
const beforeUpload: UploadProps['beforeUpload'] = rawFile => {
  if (rawFile.type !== 'video/mp4' && rawFile.type !== 'image/jpeg') {
    ElMessage({
      message: `只能上传mp4及jpg`,
      type: 'error'
    })
    return false
  }
  // if (rawFile.type === 'video/mp4') {
  //   const checkMp4 = rawFile.size / 1024 / 1024 < 50
  //   if (!checkMp4) {
  //     ElMessage({
  //       message: `视频不能大于50m`,
  //       type: 'error'
  //     })
  //     return false
  //   }
  // } else if (rawFile.type === 'image/jpeg') {
  //   const checkJpg = rawFile.size / 1024 / 1024 < 5
  //   if (!checkJpg) {
  //     ElMessage({
  //       message: `图片不能大于5m`,
  //       type: 'error'
  //     })
  //     return false
  //   }
  // }
  return true
}

const handleExceed = () => {
  ElMessageBox.alert(`当前最多只能上传${limit.value}个文件，请移除后上传！`, '错误描述', {
    confirmButtonText: '我已知晓',
    type: 'error'
  })
}

const uploadSuccess = (response: { bucketName: string; fileName: string } | undefined, uploadFile: UploadFile) => {
  if (!response) return
  uploadFile.url = '/file/' + response.bucketName + '/' + response.fileName
  let fileName = new Date().getTime() + `${fileIndex.value++}`
  let fileSuffix = uploadFile.name.split('.').pop()
  uploadFile.name = fileName + '.' + fileSuffix
  formDataArray.value.push({
    id: uploadFile.uid,
    category: 'WZ',
    type: fileSuffix?.toLocaleUpperCase() === 'MP4' ? 'VIDEO' : 'IMAGE',
    wzType: undefined,
    wzSelectData: [],
    businessId: undefined,
    fileUrl: uploadFile.url,
    fileSize: uploadFile.size || 0,
    fileName: fileName,
    fileSuffix: fileSuffix || ''
  })
}

const deleteFileList = (id: number) => {
  for (let i = 0; i < fileList.value.length; i++) {
    if (fileList.value[i].uid === id) {
      fileList.value.splice(i, 1)
      formDataArray.value.splice(i, 1)
      break
    }
  }
}

defineExpose({
  open,
  openBatch,
  close
})

const emit = defineEmits(['success'])

function sendSuccess() {
  emit('success')
}
</script>
